package com.xiubai.appforpda.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xiubai.appforpda.R;
import com.xiubai.appforpda.db.DatabaseUtils;
import com.xiubai.appforpda.entity.BaseEntity;
import com.xiubai.appforpda.entity.SQLMainPamInventBean;
import com.xiubai.appforpda.entity.SQLNCGetUseBean;
import com.xiubai.appforpda.entity.SQLOrgPersonBean;
import com.xiubai.appforpda.entity.SQLOrgStructureBean;
import com.xiubai.appforpda.entity.SQLPamAssetBean;
import com.xiubai.appforpda.entity.SQLPamInvenBean;
import com.xiubai.appforpda.entity.SQLPamLocationBean;
import com.xiubai.appforpda.entity.SQLPamStatusBean;
import com.xiubai.appforpda.entity.WebAssetEntity;
import com.xiubai.appforpda.entity.WebLocationEntity;
import com.xiubai.appforpda.entity.WebMainPamInventEntity;
import com.xiubai.appforpda.entity.WebNCGetUseEntity;
import com.xiubai.appforpda.entity.WebOrgStructureEntity;
import com.xiubai.appforpda.entity.WebPamInventEntity;
import com.xiubai.appforpda.entity.WebPamStatusEntity;
import com.xiubai.appforpda.entity.WebPersonEntity;
import com.xiubai.appforpda.event.CloseEvent;
import com.xiubai.appforpda.jack.utils.AppConstants;
import com.xiubai.appforpda.jack.utils.JsonParser;
import com.xiubai.appforpda.jack.utils.SharedPreferenceTool;
import com.xiubai.appforpda.jack.utils.Trace;
import com.xiubai.appforpda.jack.utils.WebServiceDataUtils;
import com.xiubai.appforpda.utils.ClickUtil;
import com.xiubai.appforpda.utils.ScreenUtils;
import com.xiubai.appforpda.webutils.WebServiceHelper;
import com.xiubai.appforpda.widget.CustomDialog;
import com.xiubai.appforpda.widget.CustomDialogListener;

import org.greenrobot.eventbus.EventBus;
import org.ksoap2.serialization.SoapObject;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author: r3562939
 * @version: V1.0
 * @project: AppForPda
 * @description: description
 * @date: 2018/11/13
 * @time: 13:09
 */
public class HomeActivity extends BaseActivity implements View.OnClickListener {

    private View tv_assets_use;
    private View tv_data_sync;
    private View tv_data_return;
    private View tv_assets_check;
    private View tv_assets_quit;
    private TextView tv_name;
    private CustomDialog customDialog;
    private int count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        initView();
        initData();

        SyncService.actionIntent(this,true);
    }

    @Override
    protected void onDestroy() {
        SyncService.actionIntent(this,false);
        super.onDestroy();
    }

    private void initData() {


        tv_name.setText("经办人: " + AppConstants.USER_NAME);
/*        Message message = Message.obtain();
        message.what = 0;
        message.obj = AppConstants.GET_ORG_DEPT;
        handler.sendMessage(message);*/
    }

    private void callWS(String url) {
        Trace.d("url====" + url);
        //通过工具类调用WebService接口
        LinkedHashMap<String, String> value = WebServiceDataUtils.getParameterData(url, "1=1");
        WebServiceHelper.callWebService(WebServiceHelper.WEB_URL, AppConstants.METHOD_NAME, value, new WebServiceHelper.WebServiceCallBack() {
            @Override
            public void callBack(SoapObject result) {
                Trace.d("result==" + result);
                if (result != null) {
                    String json = result.getProperty(0).toString();
                    Trace.d("json====" + json);
                    BaseEntity assetBean = JsonParser.deserializeByJson(json, BaseEntity.class);
                    if (assetBean != null) {
                        if (assetBean.isSuccess()) {
                            // do something
                            Trace.d("成功!");
                            count++;
                            Message message = Message.obtain();
                            message.what = 0;
                            switch (count) {
                                case 1:
                                    WebOrgStructureEntity webOrgStructureEntity = JsonParser.deserializeByJson(json, WebOrgStructureEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLOrgStructureBean.class);
                                    DatabaseUtils.getHelper().saveAll(webOrgStructureEntity.getV_org_dept());
                                    message.obj = AppConstants.GET_PERSON;
                                    break;
                                case 2:
                                    WebPersonEntity webPersonEntity = JsonParser.deserializeByJson(json, WebPersonEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLOrgPersonBean.class);
                                    DatabaseUtils.getHelper().saveAll(webPersonEntity.getOrg_psn());
                                    message.obj = AppConstants.GET_PAM_LOCATION;
                                    break;
                                case 3:
                                    WebLocationEntity webLocationEntity = JsonParser.deserializeByJson(json, WebLocationEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamLocationBean.class);
                                    DatabaseUtils.getHelper().saveAll(webLocationEntity.getPam_loc());
                                    message.obj = AppConstants.GET_PAM_STATUS;
                                    break;
                                case 4:
                                    WebPamStatusEntity pamStatusBean = JsonParser.deserializeByJson(json, WebPamStatusEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamStatusBean.class);
                                    DatabaseUtils.getHelper().saveAll(pamStatusBean.getPam_sta());
                                    message.obj = AppConstants.GET_ASSET_DATA;
                                    break;
                                case 5:
                                    WebAssetEntity webAssetEntity = JsonParser.deserializeByJson(json, WebAssetEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamAssetBean.class);
                                    DatabaseUtils.getHelper().saveAll(webAssetEntity.getPam_asset());
                                    message.obj = AppConstants.PAM_INVEN;
                                    break;
                                case 6:
                                    WebPamInventEntity webPamInventEntity = JsonParser.deserializeByJson(json, WebPamInventEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamInvenBean.class);
                                    DatabaseUtils.getHelper().saveAll(webPamInventEntity.getPam_inven());
                                    message.obj = AppConstants.PAM_INVEN_B;
                                    break;
                                case 7:
                                    WebMainPamInventEntity webMainPamInventEntity = JsonParser.deserializeByJson(json, WebMainPamInventEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLMainPamInventBean.class);
                                    DatabaseUtils.getHelper().saveAll(webMainPamInventEntity.getPam_inven_b());
                                    message.obj = AppConstants.GET_USE_APPLY;
                                    break;
                                case 8:
                                    WebNCGetUseEntity webNCGetUseEntity = JsonParser.deserializeByJson(json, WebNCGetUseEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLNCGetUseBean.class);
                                    DatabaseUtils.getHelper().saveAll(webNCGetUseEntity.getV_pam_assign());
                                    break;

                            }
                            if (count >= 8) {
                                return;
                            }
                            handler.sendMessage(message);

                        } else {
                            Toast.makeText(HomeActivity.this, "失败" + assetBean.status + "原因" + assetBean.msg, Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    Toast.makeText(HomeActivity.this, "没有返回", Toast.LENGTH_SHORT).show();

                }

            }
        });
    }


    private static final int GET_ORG = 0;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_ORG:
                    String url = (String) msg.obj;
                    callWS(url);
                    break;
            }
        }
    };

    private void initView() {
        EventBus.getDefault().post(new CloseEvent());
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_data_sync = findViewById(R.id.tv_data_sync);
        tv_assets_use = findViewById(R.id.tv_assets_use);
        tv_data_return = findViewById(R.id.tv_data_return);
        tv_assets_check = findViewById(R.id.tv_assets_check);
        tv_assets_quit = findViewById(R.id.tv_assets_quit);

        tv_assets_use.setOnClickListener(this);
        tv_data_sync.setOnClickListener(this);
        tv_data_return.setOnClickListener(this);
        tv_assets_check.setOnClickListener(this);
        tv_assets_quit.setOnClickListener(this);

        LinearLayout ll_layout_bottom = (LinearLayout) findViewById(R.id.ll_layout_bottom);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ll_layout_bottom.getLayoutParams();
        layoutParams.height = (int) (ScreenUtils.getScreenHeight(this) * 0.6f);
        ll_layout_bottom.setLayoutParams(layoutParams);

        // 非资产管理处人员 只有盘点权限
        if(!AppConstants.ASSET_DEPT_CODE.equals(AppConstants.DEPT_CODE)){
            tv_assets_use.setVisibility(View.GONE);
            tv_data_return.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View view) {
        if (ClickUtil.isFastDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_data_sync:
                doSync();
                break;
            case R.id.tv_assets_use:
                doGetUse();
                break;
            case R.id.tv_data_return:
                doReturnEquipment();
                break;
            case R.id.tv_assets_check:
                doCheckAssets();
                break;
            case R.id.tv_assets_quit:
                startActivity(new Intent(HomeActivity.this, MainActivity.class));
                finish();
                break;
        }
    }

    /**
     * 资产盘点
     */
    private void doCheckAssets() {
        Intent intent = new Intent(this, CheckAssetsActivity.class);
        startActivity(intent);
    }

    /**
     * 归还设备
     */
    private void doReturnEquipment() {
        Intent intent = new Intent(this, ReturnEquipmentActivity.class);
        startActivity(intent);
    }

    /**
     * 资产领用
     */
    private void doGetUse() {
        /*showAssetsGetUseDialog();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (customDialog != null && customDialog.isShowing()) {
                    customDialog.dismiss();
                }
                Intent intent = new Intent(HomeActivity.this, GetUseActivity.class);
                startActivity(intent);
            }
        }, 3000);*/

        Intent intent = new Intent(HomeActivity.this, GetUseActivity.class);
        startActivity(intent);

    }

    private void showAssetsGetUseDialog() {
        customDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        customDialog.setView(LayoutInflater.from(this).inflate(R.layout.main_promt_layout, null));
        View id = customDialog.findId(R.id.btn_back);
        if (id != null) {
            id.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (ClickUtil.isFastDoubleClick()) {
                        return;
                    }
                    customDialog.dismiss();
                }
            });
        }
        customDialog.setCanceledOutside(false);
        customDialog.show();

        dialogMatchWindow();
    }

    private void dialogMatchWindow() {
        Window window = customDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
    }

    private void doSync() {
        Intent intent = new Intent(this, SyncActivity.class);
        startActivity(intent);
    }

    //声明一个long类型变量：用于存放上一点击“返回键”的时刻
    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
            } else {
                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onPause() {
        super.onPause();

        AppConstants.IS_IN_MAIN = false;
    }

    @Override
    protected void onResume() {
        super.onResume();

        AppConstants.IS_IN_MAIN = true;
    }
}
